package com.jdz.service.impl;

import com.jdz.common.ServerResponse;
import com.jdz.dao.GroupMapper;
import com.jdz.pojo.Group;
import com.jdz.service.IGroupService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Transactional
@Service("IGroupService")
public class GroupServiceImpl implements IGroupService {

    @Autowired
    GroupMapper groupMapper;


    /**
     * 列出所有用户分组
     * @return
     */
    public ServerResponse list(){
        List<Group> groupList = groupMapper.selectAll();
        return ServerResponse.createBySuccess(groupList);
    }

    /**
     * 删除用户分组
     * @param groupno
     * @return
     */
    public ServerResponse delete(Integer groupno){

        if(groupno==0||groupno==null){
            return ServerResponse.createByErrorMessage("参数错误");
        }

        if(groupno == 1){
            return ServerResponse.createByErrorMessage("不能删除用户分组");
        }
        if(groupno == 3){
            return ServerResponse.createByErrorMessage("不能删除超级管理员分组");
        }

        int row = groupMapper.deleteByPrimaryKey(groupno);
        if(row<=0){
            return ServerResponse.createByErrorMessage("删除分组失败");
        }
        return ServerResponse.createBySuccessMessage("删除分组成功");
    }

    /**
     * 添加分组
     * @param group
     * @return
     */
    public ServerResponse add(Group group){

        if(group==null){
            return ServerResponse.createByErrorMessage("参数错误");
        }

        group.setGroupno(null);
        group.setCreattime(new Date());

        int row = groupMapper.insertSelective(group);
        if(row<=0){
            return ServerResponse.createByErrorMessage("添加分组失败");
        }
        return ServerResponse.createBySuccessMessage("添加分组成功");
    }

    /**
     * 修改分组
     * @param groupno
     * @param groupname
     * @return
     */
    public ServerResponse update(Integer groupno,String groupname){

        if(groupno==0||groupno==null|| StringUtils.isBlank(groupname)){
            return ServerResponse.createByErrorMessage("参数错误");
        }


        if(groupno == 1){
            return ServerResponse.createByErrorMessage("不能修改用户分组");
        }
        if(groupno == 3){
            return ServerResponse.createByErrorMessage("不能修改超级管理员分组");
        }

        Group group = new Group();
        group.setGroupno(groupno);
        group.setGroupname(groupname);
        int row = groupMapper.updateByPrimaryKeySelective(group);
        if(row<=0){
            return ServerResponse.createByErrorMessage("修改分组失败");
        }
        return ServerResponse.createBySuccessMessage("修改分组成功");
    }

}
